package com.qhong.interceptor;


import com.qhong.annotation.AuthIgnore;
import com.qhong.util.JwtUtils;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;


/**
 * Created by qhong on 2018/6/7 15:36
 **/
@Component
public class AuthorizationInterceptor extends HandlerInterceptorAdapter {
	@Autowired
	private JwtUtils jwtUtils;

	public static final String USER_KEY = "userId";

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		AuthIgnore annotation;
		if(handler instanceof HandlerMethod) {
			annotation = ((HandlerMethod) handler).getMethodAnnotation(AuthIgnore.class);
		}else{
			return true;
		}

		//如果有@AuthIgnore注解，则不验证token
		if(annotation != null){
			return true;
		}

		//获取用户凭证
		String token = request.getHeader(jwtUtils.getHeader());
		if(StringUtils.isBlank(token)){
			token = request.getParameter(jwtUtils.getHeader());
		}

//		//token凭证为空
//		if(StringUtils.isBlank(token)){
//			throw new AuthException(jwtUtils.getHeader() + "不能为空", HttpStatus.UNAUTHORIZED.value());
//		}
//
//		Claims claims = jwtUtils.getClaimByToken(token);
//		if(claims == null || jwtUtils.isTokenExpired(claims.getExpiration())){
//			throw new AuthException(jwtUtils.getHeader() + "失效，请重新登录", HttpStatus.UNAUTHORIZED.value());
//		}
//
//		//设置userId到request里，后续根据userId，获取用户信息
//		request.setAttribute(USER_KEY, Long.parseLong(claims.getSubject()));

		return true;
	}
}
